package org.daidai.abstrusewriting.homepage.top.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.daidai.abstrusewriting.R;
import org.daidai.abstrusewriting.homepage.top.model.ListItem;

import java.util.List;

/**
 * Created by liuch on 2016/10/31.
 */

public class ListItemAdapter extends BaseAdapter {

    private static Context context;
    private List<ListItem> list;

    public ListItemAdapter(Context context, List<ListItem> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        if (list != null) {
            return list.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (list != null) {
            return list.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View ret = null;
        if (convertView != null) {
            ret = convertView;
        } else {
            ret = LayoutInflater.from(context).inflate(R.layout.top_item, parent, false);
        }

        ViewHolder holder = (ViewHolder) ret.getTag();
        if (holder == null) {
            holder = new ViewHolder(ret);
            ret.setTag(holder);
        }

        holder.bindView(list.get(position));

        return ret;
    }

    public static class ViewHolder {

        private final ImageView imageView;
        private final TextView txtTitle;
        private final TextView txtDemo1;
        private final TextView txtDemo2;

        public ViewHolder(View item) {
            imageView = ((ImageView) item.findViewById(R.id.top_item_image));
            txtTitle = ((TextView) item.findViewById(R.id.top_item_title));
            txtDemo1 = ((TextView) item.findViewById(R.id.top_item_demo_1));
            txtDemo2 = ((TextView) item.findViewById(R.id.top_item_demo_2));
        }

        public void bindView(ListItem item) {
            Picasso.with(context).load(item.getCoverPath()).resize(65 , 65).into(imageView);
            txtTitle.setText(item.getTitle());
            txtDemo1.setText(item.getFirstKResults().get(0).getTitle());
            txtDemo2.setText(item.getFirstKResults().get(1).getTitle());
        }
    }
}
